package config

import (
	"fmt"

	yaml "github.com/asim/go-micro/plugins/config/encoder/yaml/v3"
	"github.com/asim/go-micro/v3/config"
	"github.com/asim/go-micro/v3/config/reader"
	"github.com/asim/go-micro/v3/config/reader/json"
	"github.com/asim/go-micro/v3/config/source/file"
	"github.com/asim/go-micro/v3/logger"
)

var (
	G_runmode   string //模式
	G_appname   string //名称
	G_version   string //版本
	G_httpaddr  string //web
	G_mysqldsn  string //mysql dsn
	G_redisaddr string //redis
	G_redispwd  string //redis pwd
	G_etcdaddr  string //etcd

	// 所有微服务定义
	ProgramDownloadSrv  = "go.micro.srv.ProgramDownload"
	ProgramLatestSrv    = "go.micro.srv.ProgramLatest"
	ProgramListSrv      = "go.micro.srv.ProgramList"
	ProgramRollbackSrv  = "go.micro.srv.ProgramRollback"
	ProgramUploadSrv    = "go.micro.srv.ProgramUpload"
	UserLoginSrv        = "go.micro.srv.UserLogin"
	UserLogoutSrv       = "go.micro.srv.UserLogout"
	UserRefreshTokenSrv = "go.micro.srv.UserRefreshToken"
	UserRegisterSrv     = "go.micro.srv.UserRegister"
	WebSrv              = "go.micro.srv.web"

	// JWT 钥匙
	JWTSecret = "mUxNAeHzb2fETByFt0dMgn9vwuQ46ZV5qWrRihpKLGskYjolOI"
	// 微服务token过滤
	SrvTokenFilter = []string{
		"UserLogin.Call",
		"UserRegister.Call",
		"UserRefreshToken.Call",
		"ProgramDownload.Call",
		"ProgramLatest.Call",
	}
	// web api服务token过滤
	WebTokenFilter = []string{
		"/swagger/",
		"/user/login",
		"/user/register",
		"/user/refreshToken",
		"/program/download",
		"/program/latest",
	}
)

func init() {
	enc := yaml.NewEncoder()

	c, _ := config.NewConfig(
		config.WithReader(
			json.NewReader(
				reader.WithEncoder(enc),
			),
		),
	)

	if err := c.Load(file.NewSource(
		file.WithPath("./conf/app.yaml"),
	)); err != nil {
		logger.Fatal(err)
		return
	}

	G_runmode = c.Get("runmode").String("")
	G_appname = c.Get("appname").String("")
	G_version = c.Get("version").String("")
	G_httpaddr = fmt.Sprintf(":%v",
		// c.Get(G_runmode, "web", "address").String(""),
		c.Get(G_runmode, "web", "port").Int(8080),
	)
	G_mysqldsn = fmt.Sprintf("%v:%v@tcp(%v:%v)/%v?charset=utf8mb4&parseTime=True&loc=Local",
		c.Get(G_runmode, "database", "user").String(""),
		c.Get(G_runmode, "database", "password").String(""),
		c.Get(G_runmode, "database", "address").String(""),
		c.Get(G_runmode, "database", "port").Int(3306),
		c.Get(G_runmode, "database", "database").String(""),
	)
	G_redisaddr = fmt.Sprintf("%v:%v",
		c.Get(G_runmode, "redis", "address").String(""),
		c.Get(G_runmode, "redis", "port").Int(6379),
	)
	G_redispwd = c.Get(G_runmode, "redis", "password").String("")
	G_etcdaddr = fmt.Sprintf("%v:%v",
		c.Get(G_runmode, "etcd", "address").String(""),
		c.Get(G_runmode, "etcd", "port").Int(2379),
	)
}
